package hibernatemock;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionUtil {

	public void setProperty(Object obj, Field field, Object value) {
		try {
			field.setAccessible(true);
			field.set(obj, value);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public void setProperty(Object obj, String field, Object value) {
		try {
			setProperty(obj, obj.getClass().getDeclaredField(field), value);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	public Object getProperty(Object obj, Field field) {
		try {
			field.setAccessible(true);
			return field.get(obj);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public Field getField(Class<?> clazz, String fieldName) {
		try {
			return clazz.getDeclaredField(fieldName);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public boolean isUserType(Class<?> clazz) {
		return clazz.getClassLoader() != null;
	}

	public boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotation) {
		if (field.isAnnotationPresent(annotation)) {
			return true;
		} else {
			try {
				String getterName = "get" + field.getName().substring(0, 1).toUpperCase()
						+ field.getName().substring(1);
				Class<?>[] parameter = null;
				Method method = field.getDeclaringClass().getMethod(getterName, parameter);
				if (method.isAnnotationPresent(annotation))
					return true;
			} catch (Exception e) {
				// no getter
			}
		}
		return false;
	}

}
